package com.zhen.readinglist.controller;

import com.zhen.readinglist.entity.Book;
import com.zhen.readinglist.entity.Reader;
import com.zhen.readinglist.properties.AmazonProperties;
import com.zhen.readinglist.repository.ReadingListRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: zhen-desktop
 * Date: 2019/1/22
 * Time: 20:57
 */
@Controller
@RequestMapping("/")
public class ReadingListController {

    private AmazonProperties amazonProperties;

    private ReadingListRepository readingListRepository;



    @Autowired
    public ReadingListController(ReadingListRepository readingListRepository,AmazonProperties amazonProperties){
        this.readingListRepository = readingListRepository;
        this.amazonProperties = amazonProperties;
    }

    @RequestMapping(method = RequestMethod.GET)
    private String readersBooks(Reader reader, Model model){
        List<Book> readingList = readingListRepository.findByReader(reader);
        if(readingList != null){
            model.addAttribute("books",readingList);
            model.addAttribute("reader",reader);
            model.addAttribute("amazonID",amazonProperties.getAssociateId());
        }
        return "readingList";
    }

    @RequestMapping(method = RequestMethod.POST)
    private String addToReadingList(Reader reader,Book book){
        book.setReader(reader);
        readingListRepository.save(book);
        return "redirect:/";
    }
}
